import { setCanvas } from "./setCanvas"
import { Query } from "./queryevent"
var high_source = new ol.source.Vector({})
var source = new ol.source.Vector({})
let draw
// 定义回调,作用域全局
var callback1
function Search({ map, callback }) {
  // 接收传过来的回调
  callback1 = callback
  /* 设置高亮图层-显示查询到的要素 */
  let canvas = setCanvas(map.value)
  var style = new ol.style.Style({
    image: new ol.style.Icon({
      img: canvas,
      imgSize: [canvas.width, canvas.height],
    }),
  })

  // high_source.value = new ol.source.Vector({})
  var high_layer = new ol.layer.Vector({
    source: high_source,
    title: "高亮图层",
    style,
  })
  map.value.addLayer(high_layer)

  activeDraw(map, callback)
}
function activeDraw(map) {
  //创建画布
  var style = new ol.style.Style({
    fill: new ol.style.Fill({
      color: "rgba(255,255,255,.1)",
    }),
    stroke: new ol.style.Stroke({
      color: "rgba(255,255,255,.1)",
      width: 3,
    }),
  })
  var layer = new ol.layer.Vector({
    source: source,
    style,
  })
  map.value.addLayer(layer)

  draw = createDraw({
    type: "Box",
    source: source,
  })
  map.value.addInteraction(draw)
  draw.on("drawend", function (evt) {
    // source.value.clear()
    /* 1、拉框查询获取几何信息 */
    var geometry = evt.feature.getGeometry()
    var service = {
      name: "guanggu",
      layerId: 2,
    }
    /* 2、根据几何信息调用中地接口,实现要素查询 */
    Query.queryByGeom({
      geometry,
      service,

      callback: handleQuery,
    })

    draw.setActive(false) //画笔失活
    // map.value.removeInteraction(draw)
  })
}
function handleQuery(features) {
  // 判断是否查询到结果
  if (features) {
    high_source.clear()
    source.clear()
    high_source.addFeatures(features)
    callback1(features)
  } else {
    high_sourceClear()
  }
}

function high_sourceClear() {
  draw.setActive(false) //画笔失活
  high_source.clear()
  source.clear()
}
export { Search, high_sourceClear }
